import { materialAdd, materialDel, materialPage, materialUpdate } from '@/api/baseData/materialMaintenance';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';

interface materiaLRecord {
	id: string;
	createTime?: string;
	updateUser?: string;
	updateTime?: string;
	createUser?: string;
	materiaLingCode: string;
	materiaLingType: string;
	materiaLingInventoryType?: string; // 新建字段
	description?: string;
	activate?: boolean;
	isDeleted?: boolean;
	clazz?: string;
	materialType?: string;
	materialName?: string;
	materialNo?: string;
	materialProperties?: string;
	basicUnit?: string;
	conversionUnit?: string;
	weightNumConvert?: string;
	oneMaterialWeight?: number;
}

interface materialPageResult {
	records: materiaLRecord[];
	total: number;
	size: number;
	current: number;
	optimizeCountSql: boolean;
	searchCount: boolean;
	pageSize: number;
}

interface ApiResponse<T> {
	code: number;
	message: string;
	data: T;
}

interface PaginationParams {
	current: number;
	pageSize: number;
}

interface FormData {
	materialName: string;
	materialNo: string;
	materialType: string;
	materialProperties: string;
	basicUnit: string;
	conversionUnit: string;
	weightNumConvert: string;
	oneMaterialWeight: number;
}

export function useMaterialata() {
	const searchParam = ref({});
	const isLoading = ref(true);
	const searchFields = ref([
		{
			name: 'materialName',
			label: '物料名称',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		},
		{
			name: 'materialType',
			label: '物料类型',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		}
	]);
	const pageTotal = ref(0);
	const paginatedData = ref<materiaLRecord[]>([]);
	const paginationParams = ref<PaginationParams>({ current: 1, pageSize: 10 });
	const formData = ref<FormData>({
		materialName: '',
		materialNo: '',
		materialType: '',
		materialProperties: '',
		basicUnit: '',
		conversionUnit: '',
		weightNumConvert: '',
		oneMaterialWeight: 0
	});

	const ruleFormRef = ref<FormInstance>(); // 表单实例引用

	const rules = ref<FormRules<FormData>>({
		materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
		materialNo: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
		materialProperties: [{ required: true, message: '请选择物料属性', trigger: 'blur' }],
		basicUnit: [{ required: true, message: '请输入主单位', trigger: 'blur' }],
		version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
	});
	const fetchPageData = async (params: any) => {
		isLoading.value = true;
		try {
			const response = (await materialPage({
				...params,
				current: paginationParams.value.current,
				pageSize: paginationParams.value.pageSize
			})) as unknown as ApiResponse<materialPageResult>;

			if (response.code === 200) {
				const { records, total } = response.data;
				paginatedData.value = records.map((item) => {
					return {
						...item.extension,
						...item
					};
				});
				pageTotal.value = total;
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('数据获取失败');
		} finally {
			isLoading.value = false; // 数据加载完成后设置为 false
		}
	};

	onMounted(() => {
		fetchPageData(searchParam.value);
	});

	const handleSearch = () => {
		fetchPageData(searchParam.value);
	};

	const handleSizeChange = (val: number) => {
		paginationParams.value.pageSize = val;
		fetchPageData(searchParam.value);
	};

	const handleCurrentChange = (val: number) => {
		paginationParams.value.current = val;
		fetchPageData(searchParam.value);
	};

	const addmateriaL = async (data: Partial<materiaLRecord>, callback: () => void) => {
		if (ruleFormRef.value) {
			await ruleFormRef.value.validate(async (valid) => {
				if (valid) {
					const url = data?.id ? materialUpdate : materialAdd;
					const response = (await url(data)) as unknown as ApiResponse<void>;
					if (response.code === 200) {
						if (data?.id) {
							ElMessage.success('更新成功');
						} else {
							ElMessage.success('添加成功');
						}
						fetchPageData(searchParam.value);
						callback();
					} else {
						ElMessage.error(response.message);
					}
				}
			});
		}
	};

	const deletemateriaL = async (id: string) => {
		try {
			const response = (await materialDel({ ids: [id] })) as unknown as ApiResponse<void>;
			if (response.code === 200) {
				ElMessage.success('删除成功');
				fetchPageData(searchParam.value);
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('删除失败');
		}
	};

	return {
		searchParam,
		pageTotal,
		paginatedData,
		searchFields,
		isLoading,
		handleSearch,
		handleSizeChange,
		handleCurrentChange,
		addmateriaL,
		deletemateriaL,
		paginationParams,
		ruleFormRef,
		rules,
		formData
	};
}
